<template>
  <div class="admin-staff">
    <div class="header">
      <h2>员工管理</h2>
      <el-button type="primary" @click="handleAdd">新增员工</el-button>
    </div>

    <!-- 搜索筛选 -->
    <div class="filter">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
            <el-option label="护工" value="caregiver" />
            <el-option label="前台" value="reception" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="在职" value="active" />
            <el-option label="离职" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 员工列表 -->
    <div class="table">
      <el-table :data="staffList" v-loading="loading" border>
        <el-table-column prop="id" label="员工ID" width="100" align="center" />
        <el-table-column prop="name" label="员工姓名" width="120" align="center" />
        <el-table-column prop="phone" label="手机号" width="150" align="center" />
        <el-table-column prop="role" label="角色" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getRoleTag(row.role)">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="职位" width="120" align="center" />
        <el-table-column prop="level" label="等级" width="100" align="center" />
        <el-table-column prop="workStatus" label="工作状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getWorkStatusTag(row.workStatus)">
              {{ getWorkStatusText(row.workStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="elderCount" label="负责老人数" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" size="small" @click="handleStatus(row)">
              {{ row.status === 'active' ? '设为离职' : '设为在职' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="护工" value="caregiver" />
            <el-option label="前台" value="reception" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="title">
          <el-input v-model="form.title" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-input v-model="form.level" placeholder="请输入等级" />
        </el-form-item>
        <el-form-item label="工作状态" prop="workStatus">
          <el-select v-model="form.workStatus" placeholder="请选择工作状态">
            <el-option label="在岗" value="on_duty" />
            <el-option label="休假" value="on_leave" />
            <el-option label="请假" value="sick_leave" />
          </el-select>
        </el-form-item>
        <el-form-item label="登录账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入登录账号" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入登录密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getStaffList, addStaff, updateStaff, updateStaffStatus } from '@/api/staff'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()
const staffList = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  role: '',
  status: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  id: '',
  name: '',
  phone: '',
  role: '',
  title: '',
  level: '',
  workStatus: '',
  username: '',
  password: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  title: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  level: [{ required: true, message: '请输入等级', trigger: 'blur' }],
  workStatus: [{ required: true, message: '请选择工作状态', trigger: 'change' }],
  username: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }]
}

// 计算属性
const dialogTitle = ref('新增员工')

// 方法
const getRoleText = (role) => {
  const roleMap = {
    'caregiver': '护工',
    'reception': '前台',
    'admin': '管理员'
  }
  return roleMap[role] || role
}

const getRoleTag = (role) => {
  const tagMap = {
    'caregiver': 'primary',
    'reception': 'success',
    'admin': 'warning'
  }
  return tagMap[role] || ''
}

const getWorkStatusText = (status) => {
  const statusMap = {
    'on_duty': '在岗',
    'on_leave': '休假',
    'sick_leave': '请假'
  }
  return statusMap[status] || status
}

const getWorkStatusTag = (status) => {
  const tagMap = {
    'on_duty': 'success',
    'on_leave': 'warning',
    'sick_leave': 'danger'
  }
  return tagMap[status] || ''
}

const formatDate = (date) => {
  if (!date) return ''
  return date.replace('T', ' ').substring(0, 16)
}

// 加载员工列表
const loadStaffList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.current,
      size: pagination.size
    }
    const response = await getStaffList(params)
    staffList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载员工列表失败:', error)
    ElMessage.error('加载员工列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadStaffList()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.current = 1
  loadStaffList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadStaffList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  loadStaffList()
}

// 新增员工
const handleAdd = () => {
  dialogTitle.value = '新增员工'
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
  dialogTitle.value = '编辑员工'
  Object.keys(form).forEach(key => {
    form[key] = row[key] || ''
  })
  // 编辑时不显示密码
  form.password = ''
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (form.id) {
      // 编辑
      await updateStaff(form)
      ElMessage.success('编辑员工成功')
    } else {
      // 新增
      await addStaff(form)
      ElMessage.success('新增员工成功')
    }
    
    dialogVisible.value = false
    loadStaffList()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

// 状态切换
const handleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 'active' ? '设为离职' : '设为在职'}该员工吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const newStatus = row.status === 'active' ? 'inactive' : 'active'
    await updateStaffStatus(row.id, newStatus)
    ElMessage.success('操作成功')
    loadStaffList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadStaffList()
})
</script>

<style scoped>
.admin-staff {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
